package service

import (
	"encoding/json"
	"fmt"
	"choujiang/common/db"
	"choujiang/common/models"
	"choujiang/common/utils"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"strconv"
	"time"
)

type LogMgo struct {
	Id bson.ObjectId `bson:"_id"`
	model.Log
}

func SaveLog(log model.Log) {
	if log.LogType == 1 {
		LoginLog(log)
	}
	if log.LogType == 2 {
		JumpLog(log)
	}
}

func LoginLog(log model.Log) {
	if err := db.SetLoginStats(log.UniqueId); err != nil {
		fmt.Printf("LoginLog err:%+v\n", err)
	}
}

func JumpLog(log model.Log) {
	db.Mgo.Log(func(c *mgo.Collection) {
		fmt.Printf("-----------openid: %s, togame: %s", log.OpenId, log.ToGame)
		count, err := c.Find(bson.M{"openid": log.OpenId, "togame": log.ToGame, "logtype": log.LogType}).Count()
		fmt.Printf("---------------count: %d\n", count)
		if count == 0 {
			fmt.Printf("count == 0")
			log.Id = bson.NewObjectId()
			if err = c.Insert(log); err != nil {
				fmt.Printf("c.Insert(b) err:%+v\n", err)
			}
		} else {
			fmt.Printf("count > 0")
		}
	})
	return
}

func AccumCoins(userId int64, coins float64) {
	commonKey := "BoxKey::leyouboxgroupaccumkey_" + strconv.FormatInt(userId, 10)
	keyExist := db.MainRedisClient.Exists(commonKey)
	if keyExist.Val() == 1 {
		reVal := db.MainRedisClient.GetSet(commonKey, 0)
		intCoins, _ := strconv.ParseFloat(reVal.Val(), 64)
		coins += intCoins
	}
	db.MainRedisClient.Set(commonKey, coins, time.Hour*24)
}

//判断更新用户信息的时候是否有两个人
func CheckUpdateCount(gameId, openId string, userInfo *newUserInfo, encryptedData, iv string) {
	if userInfo.OpenId != openId {
		fmt.Printf("CheckUpdateCount Unnormal User ----- gameId=:%s openId=:%s userInfo=:%v encryptedData=:%s iv=:%s", gameId, openId, userInfo, encryptedData, iv)
	}
}

//通过日志接口判断是否领取奖励
//func ReceiveRewardFromJumpLog(log model.Log, token, scene string, goodsId int64) (err error) {
//	game := model.GetGameByGameId(log.ToGame)
//	user := model.GetUserByUniqueId(log.UniqueId)
//	if user == nil {
//		err = fmt.Errorf("[ReceiveRewardFromJumpLog] user does not exist")
//	}
//	if game == nil {
//		err = fmt.Errorf("[ReceiveRewardFromJumpLog] game does not exist")
//	}
//	if game.IsSdk == 0 { //不是SDK接入的游戏
//		//判断用户是否领取过奖励
//		isValid := db.Mgo.UserIdValidate(user.Id, log.ToGame)
//		if !isValid { //用户未领取过奖励
//			if token != "" { //有分享token
//				reInt, shareStruct := ValidateShareToken(token)
//				if reInt != 0 {
//					if shareStruct.UserId != user.Id { //分享与点击不是同一个人
//						uGame := model.UserGames{}
//						has, _ := db.MysqlEngine.Where("game_id=? and user_id=?", game.Id, shareStruct.UserId).Get(&uGame)
//						if has { //分享用户已经购买过游戏
//							//领取奖励
//							err = ReceiveReward(user.Id, shareStruct.UserId, game.Price)
//							if err == nil {
//								db.Mgo.SdkRewardLog(shareStruct.UserId, user.Id, user.HeadImgUrl, user.NickName, user.MiniOpenId, log.ToGame, game.Name, game.Price*0.3, game.Price*0.1, time.Now().Unix(), "leyouguanfang", user.FromChannel)
//								//记录有效点击次数
//								db.Mgo.RecordPlayDetail(user.Id, user.FromChannel, log.ToGame)
//								//记录金币来源
//								db.Mgo.WriteCoinsLog(shareStruct.UserId, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, utils.Decimal(game.Price*0.3))
//								db.Mgo.WriteCoinsLog(user.Id, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, utils.Decimal(game.Price*0.1))
//							}
//						} else {
//							if game.Special == 1 { //特价促销游戏
//								//领取奖励
//								err = ReceiveReward(user.Id, shareStruct.UserId, game.Price)
//								if err == nil {
//									db.Mgo.SdkRewardLog(shareStruct.UserId, user.Id, user.HeadImgUrl, user.NickName, user.MiniOpenId, log.ToGame, game.Name, game.Price*0.3, game.Price*0.1, time.Now().Unix(), "leyouguanfang", user.FromChannel)
//									//记录有效点击次数
//									db.Mgo.RecordPlayDetail(user.Id, user.FromChannel, log.ToGame)
//									//记录金币来源
//									db.Mgo.WriteCoinsLog(shareStruct.UserId, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, utils.Decimal(game.Price*0.3))
//									db.Mgo.WriteCoinsLog(user.Id, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, utils.Decimal(game.Price*0.1))
//								}
//							} else {
//								err = fmt.Errorf("[ReceiveRewardFromJumpLog] inviter has not purchase the game")
//							}
//						}
//					} else {
//						err = fmt.Errorf("[ReceiveRewardFromJumpLog] can not receive from oneself")
//					}
//				} else {
//					err = fmt.Errorf("[ReceiveRewardFromJumpLog] shareToken valid failed")
//				}
//			} else {
//				if scene != "" {
//					parentId := db.Mgo.GetUserIdFromScene(scene)
//					if parentId != 0 {
//						if parentId != user.Id { //分享与点击不是同一个人
//							uGame := model.UserGames{}
//							has, _ := db.MysqlEngine.Where("game_id=? and user_id=?", game.Id, parentId).Get(&uGame)
//							if has { //分享用户已经购买过游戏
//								//领取奖励
//								err = ReceiveReward(user.Id, parentId, game.Price)
//								if err == nil {
//									db.Mgo.SdkRewardLog(parentId, user.Id, user.HeadImgUrl, user.NickName, user.MiniOpenId, log.ToGame, game.Name, game.Price*0.3, game.Price*0.1, time.Now().Unix(), "leyouguanfang", user.FromChannel)
//									//记录有效点击次数
//									db.Mgo.RecordPlayDetail(user.Id, user.FromChannel, log.ToGame)
//									//记录金币来源
//									db.Mgo.WriteCoinsLog(parentId, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, utils.Decimal(game.Price*0.3))
//									db.Mgo.WriteCoinsLog(user.Id, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, utils.Decimal(game.Price*0.1))
//								}
//							} else {
//								if game.Special == 1 { //特价促销游戏
//									//领取奖励
//									err = ReceiveReward(user.Id, parentId, game.Price)
//									if err == nil {
//										db.Mgo.SdkRewardLog(parentId, user.Id, user.HeadImgUrl, user.NickName, user.MiniOpenId, log.ToGame, game.Name, game.Price*0.3, game.Price*0.1, time.Now().Unix(), "leyouguanfang", user.FromChannel)
//										//记录有效点击次数
//										db.Mgo.RecordPlayDetail(user.Id, user.FromChannel, log.ToGame)
//										//记录金币来源
//										db.Mgo.WriteCoinsLog(parentId, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, utils.Decimal(game.Price*0.3))
//										db.Mgo.WriteCoinsLog(user.Id, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, utils.Decimal(game.Price*0.1))
//									}
//								} else {
//									err = fmt.Errorf("[ReceiveRewardFromJumpLog] inviter has not purchase the game")
//								}
//							}
//						} else {
//							err = fmt.Errorf("[ReceiveRewardFromJumpLog] can not receive from oneself")
//						}
//					} else {
//						err = fmt.Errorf("[ReceiveRewardFromJumpLog] inviter missed")
//					}
//				} else {
//					goods := model.GetGoodsById(goodsId)
//					db.Mgo.SdkRewardLog(0, user.Id, user.HeadImgUrl, user.NickName, user.MiniOpenId, log.ToGame, game.Name, 0, 3, time.Now().Unix(), "leyouguanfang", user.FromChannel)
//					//记录有效点击次数
//					db.Mgo.RecordPlayDetail(user.Id, user.FromChannel, log.ToGame)
//					if goods != nil { //有goodsId 抽奖体验
//						go func() {
//							//券码数据增加
//							err = ReceiveCoupon(user, goods, 3)
//						}()
//						//记录金币来源，抽奖体验奖励3张奖券
//						db.Mgo.WriteCoinsLog(user.Id, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, 3)
//					} else { //没有goodsId 普通体验
//						go func() {
//							//券码数据增加
//							err = ReceiveCoupon(user, goods, 1)
//						}()
//						//记录金币来源，普通体验奖励1张奖券
//						db.Mgo.WriteCoinsLog(user.Id, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, 1)
//					}
//				}
//			}
//		} else {
//			err = fmt.Errorf("[ReceiveRewardFromJumpLog] user already received")
//		}
//	} else {
//		err = fmt.Errorf("[ReceiveRewardFromJumpLog] game is not sdk")
//	}
//	return
//}

//通过日志接口判断是否领取奖励
func ReceiveRewardFromJumpLog(log model.Log, token, scene string, goodsId int64) (err error) {
	game := model.GetGameByGameId(log.ToGame)
	user := model.GetUserByUniqueId(log.UniqueId)
	if user == nil {
		err = fmt.Errorf("[ReceiveRewardFromJumpLog] user does not exist")
	}
	if game == nil {
		err = fmt.Errorf("[ReceiveRewardFromJumpLog] game does not exist")
	}
	//判断用户是否领取过奖励
	isValid := db.Mgo.UserIdValidate(user.Id, log.ToGame)
	if !isValid {
		goods := model.GetGoodsById(goodsId)
		db.Mgo.SdkRewardLog(0, user.Id, user.HeadImgUrl, user.NickName, user.MiniOpenId, log.ToGame, game.Name, 0, 3, time.Now().Unix(), "leyouguanfang", user.FromChannel)
		//记录有效点击次数
		db.Mgo.RecordPlayDetail(user.Id, user.FromChannel, log.ToGame)
		if goods != nil { //有goodsId 抽奖体验
			go func() {
				//券码数据增加
				err = ReceiveCoupon(user, goods, 3)
				//记录待弹窗提示信息
				v := db.MainRedisClient.Exists(HOMEPAGE_ALERT_KEY)
				field := "user_" + strconv.FormatInt(user.Id, 10)
				if v.Val() == 1 {
					hv := db.MainRedisClient.HExists(HOMEPAGE_ALERT_KEY, field)
					if hv.Val() {
						hget := db.MainRedisClient.HGet(HOMEPAGE_ALERT_KEY, field)
						hgetVal := make([]int64, 0)
						json.Unmarshal([]byte(hget.Val()), &hgetVal)
						if !utils.Int64InSlice(hgetVal, goods.Id) {
							hgetVal = append(hgetVal, goods.Id)
							hgetJson, _ := json.Marshal(hgetVal)
							db.MainRedisClient.HSet(HOMEPAGE_ALERT_KEY, field, string(hgetJson))
						}
					} else {
						newSlice := []int64{goods.Id}
						jsonSlice, _ := json.Marshal(newSlice)
						db.MainRedisClient.HSet(HOMEPAGE_ALERT_KEY, field, string(jsonSlice))
					}
				} else {
					newSlice := []int64{goods.Id}
					jsonSlice, _ := json.Marshal(newSlice)
					db.MainRedisClient.HSet(HOMEPAGE_ALERT_KEY, field, string(jsonSlice))
				}
			}()
			//记录金币来源，抽奖体验奖励3张奖券
			db.Mgo.WriteCoinsLog(user.Id, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, 3)
		} else { //没有goodsId 普通体验
			go func() {
				//券码数据增加
				err = ReceiveNormalCoupon(user, log.ToGame)
			}()
			//记录金币来源，普通体验奖励1张奖券
			db.Mgo.WriteCoinsLog(user.Id, CONINS_EARN_COLLECT, user.NickName, game.Name, user.NickName+"体验游戏"+game.Name, 1)
		}
	} else {
		err = fmt.Errorf("[ReceiveRewardFromJumpLog] user already received")
	}
	return
}

//判断是否有锁，没有则加锁
func CheckLock(gameId, uniqueId string) bool {
	v := db.MainRedisClient.Exists("BoxKey::redislock_" + gameId + uniqueId)
	if v.Val() == 1 { //如果有锁返回结果
		return true
	}
	//无锁设置3秒内存锁
	db.MainRedisClient.Set("BoxKey::redislock_"+gameId+uniqueId, "", time.Second*3)
	return false
}
